package com.cpd.blog.common.annotation.aspect;

import com.alibaba.fastjson.JSON;
import com.cpd.blog.common.annotation.LogAnnotation;
import com.cpd.blog.common.utils.CurrentUser;
import com.cpd.blog.common.utils.HttpContextUtils;
import com.cpd.blog.common.utils.IpUtils;
import com.cpd.blog.common.utils.LogUtil;
import com.cpd.blog.dto.User.UserVo;
import com.cpd.blog.entity.Log;
import com.cpd.blog.service.LogService;
import com.cpd.blog.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 日志AOP切面 定义了通知和切点的关系
 *
 * @author Copydown
 * @date 2021/8/18 16:10
 */
@Component
@Aspect
@Slf4j
@RequiredArgsConstructor
public class LogAspect {

    private final LogService logService;

    private final UserService userService;

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.cpd.blog.common.annotation.LogAnnotation)")
    public void recordLog() {
    }

    /**
     * 环绕通知 对方法前后进行增强
     */
    @Around("recordLog()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        UserVo userVo = CurrentUser.get();
        //执行方法
        Object result = point.proceed();
        long time = System.currentTimeMillis() - beginTime;
        recordLog(point, time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint, long time) {

        UserVo userVo = CurrentUser.get();
        if (userVo == null) {
            LogUtil.log(">> AOP ===== CurrentUser 为 null =====");
            return;
        }

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);

        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();

        Long userId = Long.getLong(userVo.getId());
        String nickName = userVo.getNickname();
        String module = logAnnotation.module();
        String operation = logAnnotation.operator();
        String methodName = signature.getName();
        String className = joinPoint.getTarget().getClass().getName();
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args);
        String ip = IpUtils.getIpAddr(request);
        LocalDateTime currTime = LocalDateTime.now();
        String optMethod = className + "." + methodName + "()";

        LogUtil.log(">> AOP ===== {} =====", module, operation, ip, optMethod, params);

        if (logAnnotation.record()) {
            Log recordLog = new Log(null, userId, nickName,
                    optMethod, module, operation, params, ip, currTime);
            if (logService.recordLog(recordLog)) {
                log.info("======>AOP日志录入成功!<======");
            } else {
                log.info("======>AOP日志录入失败！<======");
            }
        }
    }
}
